import { makeAutoObservable } from 'mobx';
import { message, Modal } from 'antd';
import utilsApi from '../../../api/utilsApi';
import myImgApi from '../../../api/myImgApi';
import utils from '../../../utils/utils';
import { util } from 'fabric/*';

export interface MyImgItem {
    id: number;
    name: string;
    description?: string;
    url: string;
    size: number;
    type: string;
    order?: number;
    created_at?: string;
    updated_at?: string;
}

class MyImgStore {

    dataList: MyImgItem[] = [];
    total = 0;
    page = 1;
    pageSize = 10;
    loading = false;
    search = '';
    editOpen = false;
    setEditOpen = (editOpen: boolean) => {
        this.editOpen = editOpen;
    }
    editModalVisible = false;
    currentImg: MyImgItem | null = null;
    editingName = '';
    editingOrder: number | null = null;
    uploadLoading = false;
    editLoading = false;

    constructor() {
        makeAutoObservable(this);
        this.getMyImg();
    }

    // 获取图片列表
    getMyImg = async ({
        page = this.page,
        pageSize = this.pageSize,
        search = this.search
    }: {
        page?: number;
        pageSize?: number;
        search?: string;
    } = {}) => {
        this.loading = true;
        this.page = page;
        this.pageSize = pageSize;
        this.search = search;
        const response = await myImgApi.getMyImgList({
            page,
            pageSize,
            search: search
        });
        // 确保response.data是数组，如果不是则使用空数组
        this.dataList = response.data.data;
        this.total = response.data.total || 0;
        this.loading = false;
    };

    //上传或者修改我的图片
    writeMyImg = async (myImgData: {
        id?: number;
        name?: string;
        description?: string;
        url?: string;
        size?: number;
        type?: string;
    }) => {
        this.uploadLoading = true;
        if (!myImgData.url) {
            const files = await utils.selectFiles();
            for (const file of files) {
                const url = await utilsApi.uploadOss(file);
                await myImgApi.writeMyImg({
                    name: utils.uuid(),
                    description: myImgData.description,
                    url: url,
                    size: file.size,
                    type: file.type,
                });
            }
        } else {
            await myImgApi.writeMyImg(myImgData);
        }
        this.getMyImg({ page: 1 });
        this.uploadLoading = false;
    };

    //删除我的图片
    delMyImg = async (id: number) => {
        await myImgApi.deleteMyImg(id);
        this.getMyImg({ page: 1 });
    };

}

const myImgStore = new MyImgStore();
export default myImgStore;